package com.atguigu.lease.web.app.service.impl;

import com.atguigu.lease.model.entity.BrowsingHistory;
import com.atguigu.lease.web.app.mapper.BrowsingHistoryMapper;
import com.atguigu.lease.web.app.service.BrowsingHistoryService;
import com.atguigu.lease.web.app.vo.history.HistoryItemVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author xiongkunYang
 * @description 针对表【browsing_history(浏览历史)】的数据库操作Service实现
 * @createDate 2025-04-19 22:27:34
 */
@Service
@RequiredArgsConstructor
public class BrowsingHistoryServiceImpl extends ServiceImpl<BrowsingHistoryMapper, BrowsingHistory>
        implements BrowsingHistoryService {

    private final BrowsingHistoryMapper browsingHistoryMapper;

    @Override
    public IPage<HistoryItemVo> historyItemVoPageByUserId(long current, long size,long userId) {
        Page<HistoryItemVo> page = new Page<>(current, size);
        return this.browsingHistoryMapper.selectHistoryItemVoPageByUserId(page, userId);
    }

    /**
     * 根据用户ID和房间ID保存或更新浏览历史
     * 如果用户对特定房间的浏览历史不存在，则创建并保存新的浏览历史记录
     * 如果浏览历史存在，则更新最后浏览时间
     *
     * @param userId 用户ID
     * @param roomId 房间ID
     */
    @Override
    @Async
    public void saveHistory(Long userId, Long roomId) {
        BrowsingHistory history = super.getOne(new LambdaQueryWrapper<BrowsingHistory>()
                .eq(BrowsingHistory::getUserId, userId)
                .eq(BrowsingHistory::getRoomId, roomId));
        // 如果浏览历史不存在，则创建并保存新的浏览历史记录
        if (history == null) {
            history = new BrowsingHistory(userId, roomId, new Date());
            super.save(history);
        } else { // 如果浏览历史存在，则更新最后浏览时间
            history.setBrowseTime(new Date());
            super.updateById(history);
        }
    }
}




